const config = require("./configs.js");

const {
  generateToolbarButtons,
  generateHandlerFunctions,
} = require("./public/toolbarConfig.js");
const { spannedFile, updateMenuFile } = require("./spannedFile.js");
const { main } = require("./api/request.js");

// 工具函数：转换为帕斯卡命名
const toPascalCase = (str) => {
  return str
    .split(/[-_\s]+/)
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join("");
};

// 主界面生成
const indexVue = `<template>
  <div class="container-view">
    <div class="header-box">
      <msc-search
        ref="formRef"
        open
        :modelValue="modelValue"
        :formConfig="formConfig"
        :layout="layout"
        :schema="schema"
        :baseHeight="baseHeight"
        :default-row-num="1"
        :config-props="{ searchButtonProps: { disabled: loading } }"
        @search="search()"
        @reset="reset"
      ></msc-search>
    </div>
    <div class="table-box">
      <div class="table-view">
        <msc-table
          v-loading="loading"
          ref="tableRef"
          v-model="tableData"
          :columns="tableColumns"
          :toolbar="toolbarCustom"
          :page="pageOptions"
          :props="tableProps"
          :handle="tableHandle"
          @handle-page-change="handleChange"
          @change-column="handleColumn"
          has-pagination
          :highlightSelectedRow="{ ifHighlight: true }"
        >
          <template #toolbar>
              ${generateToolbarButtons()}
          </template>
        </msc-table>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup name="${toPascalCase(config.moduleName)}">
  import { $t } from "msct-web-sdk";
  import { ref, h } from "vue";
  import { usePageConfig } from '@/hooks/usePageConfig';
  import { useHeaderConfig } from "./hook/useHeaderConfig";
  import { useTableConfig } from "./hook/useTableConfig";
  import { pageOptionsType, recordsType } from "@/types/common";
  import { Api } from "./api";
  import { handleColumn, saveAs, useWipeOffTrim, setRecords } from "@/utils";
  import { MdMessage, MdMessageBox } from "mdesign3";
  import dayjs from "dayjs";
  import qmsBtn from "@/components/QmsBtn/index.vue";
  import { useRouter, useRoute } from "vue-router";

  const router = useRouter();
  const route = useRoute();
  const tableRef = ref();
  const loading = ref(false);

  const { baseHeight, layout, formConfig, pageOptions, toolbar } = usePageConfig();
  const { modelValue, schema } = useHeaderConfig();
  const { tableData, tableColumns, tableProps, tableHandle, tableSelected } = useTableConfig();

  const reset = () => {
    tableRef.value.tableRef.clearSelection();
    tableRef.value.setPage({ pageSize: 10, pageNo: 1, total: 0 });
  };

  /**
   * @description 分页
   * @returns { VNode }
   */
  const handleChange = (params: pageOptionsType) => {
      pageOptions.value.pageNo = params.pageNo;
      pageOptions.value.pageSize = params.pageSize;
      search();
  };

  /**
   * @description 表格顶部右侧工具
   * @returns { VNode }
   */
  const toolbarCustom = ref([
    ...toolbar.value,
    {
      type: "export",
      tip: $t("导出"),
      show: true,
      render: () => {
        return h(
          qmsBtn,
          {
            type: "primary",
            authKey: "${config.moduleName}-export",
            onClick: () => {
              exportExcel();
            },
          },
          () => $t("导出")
        );
      },
    },
  ]);

  /**
   * @description  获取列表数据
   * @returns {void}
   */
  const search = () => {
      tableRef.value.tableRef.clearSelection();
      tableData.value = [];
      const params = {
          current: pageOptions.value.pageNo,
          size: pageOptions.value.pageSize,
          ...useWipeOffTrim(modelValue.value),
      };
      loading.value = true;
      Api.getList(params)
          .then((res) => {
              const data = res.data as recordsType;
              tableData.value = setRecords(data.records) ?? [];
              pageOptions.value.total = data.total ?? 0;
              tableRef.value.setPage({ total: pageOptions.value.total });
          })
          .finally(() => (loading.value = false));
  };

  /**
   * @description 导出
   * @returns {void}
   */
  const exportExcel = () => {
    // 导出限制条件5000条
    if (pageOptions.value.total > 5000) {
        MdMessage.warning($t('超出导出限制，最大支持导出5000条，请缩小查询范围后导出!'));
        return;
    }
        
    const params = {
      ...useWipeOffTrim(modelValue.value),
    };

    loading.value = true;
    Api.exportExcel(params)
      .then((res) => {
        if (res) {
          MdMessage.success($t("导出成功"));
          const title = \`\${$t("${
            config.moduleNameValue
          }")}\${dayjs().format("YYYYMMDDHHmmss")}\`;
          saveAs(\`\${title}.xlsx\`, res);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };

  ${generateHandlerFunctions()}

  defineExpose({
      route,
      router,
  });
</script>`;

// 执行主函数
main()
  .then(() => console.log("应用程序执行完成"))
  .catch((err) => console.error("应用程序失败:", err))
  .finally(() => {
    // 优先生成Vue文件
    spannedFile(indexVue);
    updateMenuFile();
  });
